<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 14:13
 */

namespace app\logic\index\video;


use app\common\lib\Common;
use app\common\lib\Puppeteer;
use app\common\lib\RedisQueue;
use app\common\lib\TencentCos;
use app\exception\IndexException;
use app\logic\BaseLogic;
use app\model\image\ImageCommandPlanModel;
use app\model\user\UserPromotionVideoModel;
use app\model\video\AsyncUploadVideoIvldModel;
use support\Cache;

class VideoLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
//        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return  new self();
    }

    public function asyncVideoIvld($param)
    {
        //首先复制视频到本地服务器
        $name = substr(md5(round(microtime(true)*1000).uniqid()),-20);
        $filePath = runtime_path('ivld/'.date('ymd').'/'.$name.'.'.$param['ext']);
        Common::mkdirs(dirname($filePath));
        $res = copy(request()->file('file')->getRealPath(),$filePath);
        if($res==false){
            throw new IndexException(4020,'上传失败');
        }
        unlink(request()->file('file')->getRealPath());

        //生成唯一的请求id
        $requestId = Common::getRequestId();

        // 队列名
        $queue = 'asyncVideoIvld';
        // 数据，可以直接传数组，无需序列化
        $data = ['requestid'=>$requestId,'filepath'=>$filePath];
        // 投递消息
        RedisQueue::getInstance()->sendQueue($queue, $data);

        return ['requestid'=>$requestId];
    }

    public function asyncLinkVideoIvld($param)
    {
        //生成唯一的请求id
        $requestId = Common::getRequestId();

        // 队列名
        $queue = 'asyncVideoLink';
        // 数据，可以直接传数组，无需序列化
        $data = ['requestid'=>$requestId,'video_link_text'=>$param['video_link_text']];
        // 投递消息
        RedisQueue::getInstance()->sendQueue($queue, $data);

        return ['requestid'=>$requestId];
    }

    public function getAsyncVideoIvldProgress($param)
    {
        $progress = Cache::get('get_link_video_'.$param['requestid'],[]);
        if(empty($progress)){
            usleep(500000);
            $progress = Cache::get('get_link_video_'.$param['requestid'],[]);
        }
        if(!empty($progress)){
            if($progress['progress']<0){
                throw new IndexException(4020,$progress['msg']);
            }elseif($progress['progress']<100){
                return [
                    'step'=>'0',
                    'status'=>1,
                    'msg'=>$progress['msg'],
                    'progress'=>$progress['progress'],
                    'data'=>null
                ];
            }
        }

        $progress = Cache::get('uploadfile_progress_'.$param['requestid'],[]);
        if(empty($progress)){
            usleep(500000);
            $progress = Cache::get('uploadfile_progress_'.$param['requestid'],[]);

            if(empty($progress)){
                throw new IndexException(4020,'请求ID不存在');
            }
        }
        if($progress['progress']<0){
            throw new IndexException(4020,$progress['msg']);
        }elseif($progress['progress']<100){
            return [
                'step'=>'1',
                'status'=>1,
                'msg'=>'waiting upload video',
                'progress'=>$progress['progress'],
                'data'=>null
            ];
        }

        $data = Cache::get('async_vieo_ivld_'.$param['requestid'],[]);
        if($data==false){
            $data = AsyncUploadVideoIvldModel::getInstance()->getWhere(['requestid'=>$param['requestid']])->value('result');
            if($data==false){
                throw new IndexException(4020,'视频导入失败');
            }
            $data =json_decode($data, true);
        }

        $data['data'] = !empty($data['data'])?$data['data']:null;
        return $data;
    }

    public function submitData($param)
    {
        if(Common::setnx('video_submitData_'.request()->curUserId)==false){
            throw new IndexException(4020,'请求频繁');
        }

        $insert = [
            'user_sn'=>request()->curUserId,
            'video_content'=>$param['content'],
            'video_url'=>$param['video_url'],
            'modelid'=>$param['modelid']??0,
            'templateid'=>$param['templateid']??0,
            'musicid'=>$param['musicid']??0,
            'timbreid'=>$param['timbreid']??0,
            'music_volume'=>$param['music_volume']??5,
            'timbre_volume'=>$param['timbre_volume']??5,
            'speak_speed'=>$param['speak_speed']??0,
            'fontid'=>$param['fontid']??0,
            'video_rate'=>$param['video_rate']??'1:1',
            'status'=>0,
        ];
        $id = UserPromotionVideoModel::getInstance()->insertGetId($insert);

        //生成唯一的请求id
        $requestId = Common::getRequestId();

        // 队列名
        $queue = 'asyncVideoPart';
        // 数据，可以直接传数组，无需序列化
        $data = ['requestid'=>$requestId,'id'=>$id];
        // 投递消息
        RedisQueue::getInstance()->sendQueue($queue, $data);

        return ['requestid'=>$requestId,'id'=>$id];
    }

    public function getVideoAnalyzeResult($param)
    {
        $video = UserPromotionVideoModel::getInstance()->find($param['id']);
        if($video==false){
            throw new IndexException(4020,'视频分析不存在');
        }

        $count = 0;
        $parts = [];
        if($video['status']==1 && !empty($video['part_content'])){
            $parts = json_decode($video['part_content'], true);
            $count = count($parts);
        }

        $totoalPonint = round($count*config('param.image_consume_point',1));
        $message = !empty($video['message']) ? $video['message'] : '视频分析中...';

        return [
            'id'          => $param['id'], 'count' => $count, 'status' => $video['status'],
            'total_point' => $totoalPonint, 'message' => $message, 'parts' => $parts
        ];
    }
}